"""
Case Type   : 问题回归
Case Name   : 2.0.2版本数据库,设置synchronous_standby_names='',核对配置文件和数
              据库内部,是否修改成功
Create At   : 2022/11/18
Owner       : liu-tong-8848
Description :
    1.修改参数synchronous_standby_names=' '
    2.查看配置文件postgresql.conf，参数synchronous_standby_names是否生效
    3.进入数据库查询参数synchronous_standby_names是否生效
    4.清理环境
Expect      :
    1.成功
    2.生效
    3.生效
    4.成功
History     :
"""

import os
import unittest
from yat.test import Node
from yat.test import macro
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger

Primary_SH = CommonSH('PrimaryDbUser')


@unittest.skipIf(3 != Primary_SH.get_node_num(), '非1+2环境不执行')
class Tools(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.common = Common()
        self.constant = Constant()
        self.commsh = CommonSH('PrimaryDbUser')
        self.primary_node = Node('PrimaryDbUser')
        self.synchronous_standby_names = self.common.show_param(
            "synchronous_standby_names")
        self.path = os.path.join(macro.DB_INSTANCE_PATH, 'postgresql.conf')
        self.host_name = self.primary_node.sh('hostname').result().strip()

    def test_gs_upgrade(self):
        text = "step1:修改参数synchronous_standby_names=' ' expect:成功"
        self.log.info(text)
        guc_res = self.commsh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f"synchronous_standby_names=' '")
        self.log.info(guc_res)
        self.assertTrue(guc_res, '执行失败' + text)

        text = '-----step2:查看配置文件postgresql.conf,参数synchronous_standby' \
               '_names是否生效 expect:生效-----'
        self.log.info(text)
        cmd = f"cat {self.path};"
        result = self.common.get_sh_result(self.primary_node, cmd)
        self.log.info(result)
        self.assertIn("synchronous_standby_names = ''", result, '执行失败' +
                      text)

        text = '-----step3:进入数据库查询参数synchronous_standby_names是否生' \
               '效 expect:生效-----'
        self.log.info(text)
        result = self.common.show_param("synchronous_standby_names")
        self.log.info(result)
        self.assertEqual("", result, '执行失败' + text)

    def tearDown(self):
        text = '-----step4:清理环境 expect:成功-----'
        self.log.info(text)
        guc_res = self.commsh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f"synchronous_standby_names='{self.synchronous_standby_names}'",
            node_name=self.host_name)
        self.log.info(guc_res)
        self.assertTrue(guc_res, '执行失败' + text)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
